/*
 * Copyright 2013 Rivaldo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jety.client.transport;

import com.google.gson.JsonObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jety.client.AsynchronousExecutor;
import org.jety.commons.util.JsonConverter;

/**
 *
 * @author Rivaldo
 */
public class AsynchronousTransport implements Runnable {

    private URL url;
    private BufferedReader reader;
    private AsynchronousExecutor executor;

    private boolean keepRunning = Boolean.TRUE;

    public AsynchronousTransport(AsynchronousExecutor executor, URL url) {
        this.url = url;
        this.executor = executor;
    }

    @Override
    public void run() {
        try {
            listen();
        } catch (IOException ex) {
            Logger.getLogger(AsynchronousTransport.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void setKeepRunning(boolean keepRunning) {
        this.keepRunning = keepRunning;
    }

    private void listen() throws IOException {

        JsonObject callbackRequest = null;
        String inputLine;

        while ((inputLine = reader.readLine()) != null) {
            if (inputLine!=null){
                callbackRequest = JsonConverter.toJsonObject(inputLine);
                executor.execute(callbackRequest);
            }else{
                try {
                    Thread.sleep(20);
                } catch (InterruptedException ex) {
                    Logger.getLogger(AsynchronousTransport.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        reader.close();
    }

    private BufferedReader prepareReader(InputStream in) {
        InputStreamReader input = new InputStreamReader(in);
        return new BufferedReader(input);
    }

    public String call(String requestData) throws Exception {
       return post(requestData);
    }

    private String post(String data) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.addRequestProperty("Accept-Encoding", "gzip");

        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.connect();

        OutputStream out = null;

        try {
            out = connection.getOutputStream();

            out.write(data.getBytes());
            out.flush();
            out.close();

            int statusCode = connection.getResponseCode();
            if (statusCode != HttpURLConnection.HTTP_OK) {
            }
        } finally {
            if (out != null) {
                out.close();
            }
        }

        reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));

        String response = reader.readLine();

        return response;
    }

}
